package com.gzhryc.net_marketing.cloud.micro.api.controllers.v1;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.cloud.business.PayConfig;
import com.gzhryc.net_marketing.cloud.business.dao.db.TeamPayApplyMember;
import com.gzhryc.net_marketing.cloud.business.dao.enums.TeamPayApplyMemberEnum;
import com.gzhryc.net_marketing.cloud.business.services.TeamPayApplyMemberService;
import com.gzhryc.net_marketing.cloud.business.services.TeamPayApplyService;
import com.gzhryc.net_marketing.cloud.micro.api.ClientAPICodeConstants;
import com.gzhryc.net_marketing.cloud.micro.api.MicroConstants;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.team.TeamPayApplyJoinRequest;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.team.TeamPayApplyRequest;
import com.gzhryc.net_marketing.cloud.micro.api.dto.v1.team.TeamPayApplyResponse;
import com.gzhryc.pay.adaptation.weixin.DefaultWXPayConfig;
import com.gzhryc.pay.adaptation.weixin.WXPayNormalPayService;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EPayType;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.member.LoginMember;
import com.gzhryc.shared_device.oem.code.member.MemberWalletNormalPayService;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberAddress;
import com.gzhryc.shared_device.oem.code.member.dao.enums.MemberEnum;
import com.gzhryc.shared_device.oem.code.member.services.MemberAddressService;
import com.gzhryc.shared_device.oem.code.member.services.MemberService;

public class GoodsTeamPayController {
	
	static Logger log = Logger.getLogger(GoodsTeamPayController.class);

	/**
	 * 申请团拼
	 * 
	 * @param request
	 * @return
	 */
	@Route(value = { "/market/goods/team/pay/apply.do" })
	public TeamPayApplyResponse apply(HttpServletRequest request) {
		TeamPayApplyResponse apiResp = new TeamPayApplyResponse(ClientAPICodeConstants.EXECUTE_ERROR, "申请失败，请稍后再试！");
		TeamPayApplyRequest apiReq = WebUtils.getJsonRequest(request, TeamPayApplyRequest.class);
		if (apiReq != null && apiReq.getBody().getGoodsId() != null) {
			if (apiReq.getBody().getAddressId() == null) {
				apiResp.setMsg("请选择收货地址");
				return apiResp;
			}
			
			if (StringUtils.isBlank(apiReq.getBody().getAppId())
					&& apiReq.getBody().getPayType() == null) {
				apiResp.setMsg("未知的支付应用");
				return apiResp;
			}
			
			if (apiReq.getBody().getGoodsNum() == null || apiReq.getBody().getGoodsNum() <= 0) {
				apiResp.setMsg("请选择购买数量");
				return apiResp;
			}
			
			LoginMember loginMember = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, LoginMember.class);
			MemberAddress mailAddress = MemberAddressService.self(BaseConstants.JDBC_KEY).getByKeys(loginMember.getId(),apiReq.getBody().getAddressId());
			if (mailAddress == null) {
				apiResp.setMsg("收货地址不存在，请重新选择");
				return apiResp;
			}

			TeamPayApplyMember applyMember = null;
			if (StringTools.isNotBlank(apiReq.getBody().getTradeNo())) {
				log.info("团拼二次支付，订单号 = {{0}}，参与者ID = {{1}}", apiReq.getBody().getTradeNo(), loginMember.getId());
				applyMember = TeamPayApplyMemberService.self().getByBusinessTradeNo(apiReq.getBody().getTradeNo());
				if (applyMember != null && applyMember.getState() > TeamPayApplyMemberEnum.State.Participating.index()) {
					apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR, "团拼已结束");
					return apiResp;
				}
			}

			try {
				PayConfig payConfig = new PayConfig();
				payConfig.setPayType(apiReq.getBody().getPayType());
				payConfig.setAppId(apiReq.getBody().getAppId());
				payConfig.setLogisticsCompanyId(apiReq.getBody().getLogisticsCompanyId());

				if (EPayType.WXPay.index().equals(payConfig.getPayType())) {
					if (!MemberEnum.Type.WxUser.index().equals(loginMember.getType())) {
						throw new LogicException("非微信用户");
					}

					WXPayNormalPayService payService = PayServiceFactory.self().getWXPayNormalPayService(payConfig.getAppId(),EBusinessType.MARKET.index());
					DefaultWXPayConfig wxPayConfig = payService.getConfig();
					payConfig.setPayerId(loginMember.getOpenId());
					payConfig.setNotifyUrl(wxPayConfig.getPayNotifyUrl());

					if (applyMember == null) {
						payConfig.setBusinessAccount(wxPayConfig.getMchId());
						payConfig.setClientIP(WebUtils.getClientIP(request));
						payConfig.setMailAddress(mailAddress);
						log.info("发起团拼，商品ID = {{0}}，发起人ID = {{1}}", apiReq.getBody().getGoodsId(), loginMember.getId());
						
						Member member = MemberService.self(BaseConstants.JDBC_KEY).getById(loginMember.getId());
						applyMember = TeamPayApplyService.self().apply(member, apiReq.getBody().getGoodsId()
								, apiReq.getBody().getSpecificationId(), apiReq.getBody().getGoodsNum(), payConfig);
					}

					if (applyMember != null) {
						//apiResp = TeamPayControllerUtils.apply(apiResp, applyMember, payConfig, payService);
					} else {
						log.error("{{0}}会员发起{{1}}商品团拼失败，支付信息：{{0:json}}", loginMember.getId(), apiReq.getBody().getGoodsId(), payConfig);
					}


				} else if (EPayType.EWallet.index().equals(payConfig.getPayType())) {
					MemberWalletNormalPayService payService = new MemberWalletNormalPayService();
					payConfig.setPayerId(loginMember.getId().toString());

					if (applyMember == null) {
						payConfig.setClientIP(WebUtils.getClientIP(request));
						payConfig.setMailAddress(mailAddress);
						log.info("发起团拼，商品ID = {{0}}，发起人ID = {{1}}", apiReq.getBody().getGoodsId(), loginMember.getId());
						
						Member member = MemberService.self(BaseConstants.JDBC_KEY).getById(loginMember.getId());
						applyMember = TeamPayApplyService.self().apply(member, apiReq.getBody().getGoodsId()
								, apiReq.getBody().getSpecificationId(), apiReq.getBody().getGoodsNum(), payConfig);
					}

					if (applyMember != null) {
						//apiResp = TeamPayControllerUtils.apply(apiResp, applyMember, payConfig, payService);
					} else {
						log.error("{{0}}会员发起{{1}}商品团拼失败，支付信息：{{0:json}}", loginMember.getId(), apiReq.getBody().getGoodsId(), payConfig);
					}
				} else {
					throw new LogicException("未知支付类型");
				}
			} catch (LogicException e) {
				apiResp.setMsg(e.getMessage());
			}
		}
		return apiResp;
	}

	@Route(value = { "/market/goods/team/pay/join.do" })
	public TeamPayApplyResponse join(HttpServletRequest request) {
		TeamPayApplyResponse apiResp = new TeamPayApplyResponse(ClientAPICodeConstants.EXECUTE_ERROR, "参加失败，请稍后再试！");
		TeamPayApplyJoinRequest apiReq = WebUtils.getJsonRequest(request, TeamPayApplyJoinRequest.class);
		if (apiReq != null && apiReq.getBody().getGoodsId() != null) {
			if (apiReq.getBody().getAddressId() == null) {
				apiResp.setMsg("请选择收货地址");
				return apiResp;
			}
			if (StringUtils.isBlank(apiReq.getBody().getAppId())
					&& apiReq.getBody().getPayType() == null) {
				apiResp.setMsg("未知的支付应用");
				return apiResp;
			}
			if (apiReq.getBody().getGoodsNum() == null || apiReq.getBody().getGoodsNum() <= 0) {
				apiResp.setMsg("请选择购买数量");
				return apiResp;
			}
			
			LoginMember loginMember = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, LoginMember.class);
			MemberAddress mailAddress = MemberAddressService.self(BaseConstants.JDBC_KEY).getByKeys(loginMember.getId(),apiReq.getBody().getAddressId());
			if (mailAddress == null) {
				apiResp.setMsg("收货地址不存在，请重新选择");
				return apiResp;
			}

			TeamPayApplyMember applyMember = null;
			if (StringTools.isNotBlank(apiReq.getBody().getTradeNo())) {
				log.info("团拼二次支付，团拼ID = {{0}}，参与者ID = {{1}}", apiReq.getBody().getApplyId(), loginMember.getId());
				applyMember = TeamPayApplyMemberService.self().getByBusinessTradeNo(apiReq.getBody().getTradeNo());
				if (applyMember != null && applyMember.getState() > TeamPayApplyMemberEnum.State.Participating.index()) {
					apiResp.setCode(ClientAPICodeConstants.EXECUTE_ERROR, "团拼已结束");
					return apiResp;
				}
			}

			try {
				PayConfig payConfig = new PayConfig();
				payConfig.setPayType(apiReq.getBody().getPayType());
				payConfig.setAppId(apiReq.getBody().getAppId());
				payConfig.setLogisticsCompanyId(apiReq.getBody().getLogisticsCompanyId());

				if (EPayType.WXPay.index().equals(payConfig.getPayType())) {
					if (!MemberEnum.Type.WxUser.index().equals(loginMember.getType())) {
						throw new LogicException("非微信用户");
					}

					WXPayNormalPayService payService = PayServiceFactory.self().getWXPayNormalPayService(payConfig.getAppId(),EBusinessType.MARKET.index());
					DefaultWXPayConfig wxPayConfig = payService.getConfig();
					payConfig.setPayerId(loginMember.getOpenId());
					payConfig.setNotifyUrl(wxPayConfig.getPayNotifyUrl());

					if (applyMember == null) {
						payConfig.setBusinessAccount(wxPayConfig.getMchId());
						payConfig.setClientIP(WebUtils.getClientIP(request));
						payConfig.setMailAddress(mailAddress);
						log.info("参加团拼，团拼ID = {{0}}，参与者ID = {{1}}", apiReq.getBody().getApplyId(), loginMember.getId());
						
						Member member = MemberService.self(BaseConstants.JDBC_KEY).getById(loginMember.getId());
						applyMember = TeamPayApplyService.self().join(member, apiReq.getBody().getApplyId()
								, apiReq.getBody().getSpecificationId(), apiReq.getBody().getGoodsNum(), payConfig);
					}

					if (applyMember != null) {
						//apiResp = TeamPayControllerUtils.apply(apiResp, applyMember, payConfig, payService);
					} else {
						log.error("{{0}}会员添加{{1}}商品团拼失败，支付信息：{{0:json}}", loginMember.getId(), apiReq.getBody().getGoodsId(), payConfig);
					}
				} else if (EPayType.EWallet.index().equals(payConfig.getPayType())) {
					MemberWalletNormalPayService payService = new MemberWalletNormalPayService();
					payConfig.setPayerId(loginMember.getId().toString());

					if (applyMember == null) {
						payConfig.setClientIP(WebUtils.getClientIP(request));
						payConfig.setMailAddress(mailAddress);
						log.info("参加团拼，团拼ID = {{0}}，参与者ID = {{1}}", apiReq.getBody().getApplyId(), loginMember.getId());
						
						Member member = MemberService.self(BaseConstants.JDBC_KEY).getById(loginMember.getId());
						applyMember = TeamPayApplyService.self().join(member, apiReq.getBody().getApplyId()
								, apiReq.getBody().getSpecificationId(), apiReq.getBody().getGoodsNum(), payConfig);
					}

					if (applyMember != null) {
						//apiResp = TeamPayControllerUtils.apply(apiResp, applyMember, payConfig, payService);
					} else {
						log.error("{{0}}会员添加{{1}}商品团拼失败，支付信息：{{0:json}}", loginMember.getId(), apiReq.getBody().getGoodsId(), payConfig);
					}
				} else {
					throw new LogicException("未知支付类型");
				}
			} catch (LogicException e) {
				apiResp.setMsg(e.getMessage());
			}
		}
		return apiResp;
	}
}
